package com.liull.netty.lagou.write_and_flush;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @Author: liull
 * @Description: 服务端 用于理解 writeAndFlush()方法 1.为什么要write and flush ,flush之前数据存放在哪儿？ 2.writeAndFlush是如何出发事件传播的，数据时怎么写到Socket底层的
 *               3.writeAndFlush是同步和异步，它是线程安全的吗
 * @Date: Created in 22:00 2020/12/28
 * @Modified By:
 */
public class EchoServer {
    public static void main(String[] args) throws InterruptedException {
        new EchoServer().startEchoServer(8099);
    }

    public void startEchoServer(int port) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // 配置channel类型
                    .handler(new LoggingHandler(LogLevel.INFO)) // 设置serverSocketChannel对应的Handler
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new FixedLengthFrameDecoder(10));
                            ch.pipeline().addLast(new ResponseSampleEncoder());
                            ch.pipeline().addLast(new RequestSampleHandler());
                        }
                    });
            // bind() 才是真正进行服务器端口绑定和启动的入口，sync() 表示阻塞等待服务器启动完成。
            ChannelFuture channelFuture = sb.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
